package edu.zzu.servideImpl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.zzu.Entity.PackageRoute;
import edu.zzu.Entity.PackageRouteDetail;
import edu.zzu.dao.PackageRouteDao;
import edu.zzu.mapper.PackageRouteMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@Component
public class PackageRouteService implements edu.zzu.service.PackageRouteService {

    @Autowired
    private PackageRouteDao packageRouteDao;

    @Autowired
    private ObjectMapper jsonMapper;

    @Override
    public String getPackageRouteByPackageId(String id) {
        try {
            return jsonMapper.writeValueAsString(packageRouteDao.getPackageRouteById(id));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }


        return null;
    }

    @Override
    public String getPackageRouteDetailByPackageId(String id) {
        List<PackageRoute> packageRouteById = packageRouteDao.getPackageRouteById(id);

        List<PackageRouteDetail> res=new ArrayList<>();
        for (PackageRoute packageRoute : packageRouteById) {
            PackageRouteDetail packageRouteDetail = new PackageRouteDetail();
            packageRouteDetail.setId(packageRoute.getId());
            packageRouteDetail.setHandler(packageRoute.getHandler());
            packageRouteDetail.setPackageId(packageRoute.getPackageId());
            packageRouteDetail.setStatus(packageRoute.getStatus());
            packageRouteDetail.setTime(packageRoute.getTime());
            if (packageRoute.getTransNodeId()!=null) {
                packageRouteDetail.setTransNode(getAddressByTransNodeId(packageRoute.getTransNodeId()));
            }

            packageRouteDetail.setX(packageRoute.getX());
            packageRouteDetail.setY(packageRoute.getY());
            res.add(packageRouteDetail);
        }
        try {
            return jsonMapper.writeValueAsString(res);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public String getAddressByTransNodeId(Long id) {
        return packageRouteDao.selectAddressByTransNodeId(id);
    }
}
